<template>
  <t-drawer :visible="visibleDrawer" :closeOnOverlayClick="false" :closeBtn="true" size="large" header="使用AI生成文案" :footer="null" @close="onClose">
    <t-space direction="vertical" style="width:100%">
      <t-textarea v-model="txt" :autosize="{ minRows: 3, maxRows: 5 }" placeholder="想生成什么文案,在这里给AI一个提示" style="width:100%"></t-textarea>
      <t-space>
        <t-button v-if="chatStatus==0" @click="start(null)" :disabled="chatStatus==1">开始生成</t-button>
        <t-button v-else @click="start(null)" :disabled="chatStatus==1">AI正在创作...</t-button>

        <t-button theme="default" @click="onClose()" >关闭AI</t-button>
      </t-space>

    </t-space>
<t-divider>以下内容由AI生成</t-divider>
<t-space>
  {{articleContent}}
</t-space>


<t-space direction="vertical" style="margin-top:10px">
  <t-link v-for="item in followUp" @click="start(item)">
  <template #suffix-icon>
            <jump-icon />
          </template>
  {{item}}</t-link>
</t-space>

    </t-drawer>

</template>

<script setup>
  import {ref,watch} from 'vue'
  import {useRouter} from 'vue-router'
  import {MessagePlugin,DialogPlugin} from 'tdesign-vue-next'
  import {JumpIcon} from 'tdesign-icons-vue-next'
  import {conversation,sendMsg,Retry,MessageList} from '@/api/chat'

  const router=useRouter()
  const txt=ref('')
  const articleContent=ref('')
  const visibleDrawer=ref(false)
  const followUp=ref([]) //相关
  const props=defineProps({
    visible:{
      type:Boolean
    }
  })
  const emits=defineEmits(['onClose','onComplete'])
  const chatContext=ref({
    conversation_id:'',
    chat_id:''
  })
  const chatStatus=ref(0)

  const onClose=()=>{
    visibleDrawer.value=false
    emits('onClose')
  }

  const start=async (text)=>{
     let id=localStorage.getItem('conversationId')
     if(!id)
     {
        id= await getConversation();
     }else
     id= await getConversation();

     if(text)
     {
       txt.value=text
     }
    if(id&&id!='')
     {
        await AIArticle(id)
     }

  }


  const getConversation=async()=>{
    let conversationId='';
    await conversation({content:''})
          .then(ret=>{
            console.log('ret',JSON.stringify(ret))
            if(ret.success==false)
            {
              MessagePlugin.error(ret.msg)
              if(ret.code==5401)
              {
                MessagePlugin.error('请前往【设置】-【Token设置】，申请token后再使用AI')
              }
              return conversationId;
            }
            if(ret.success==true)
            {
              localStorage.setItem('conversationId',ret.result.data.id)
              conversationId= ret.result.data.id;
            }

          }).catch(e=>{
            if(e.message)
            {
              MessagePlugin.error(e.message)

            }else
            {
              MessagePlugin.error(e.msg)
            }
          });

    return conversationId;
  }
  const AIArticle=async(conversationId)=>{
    var data={
      conversation_id:conversationId,
      content_type:'text',
      content:txt.value
    }
    sendMsg(data)
    .then(ret=>{
      MessagePlugin.success('AI生成中...')
      chatStatus.value=1
      chatContext.value={
        conversation_id:ret.result.data.conversation_id,
        chat_id:ret.result.data.id
      }

      let timer= setInterval(()=>{
        Retry(chatContext.value)
        .then(ret2=>{
          if(ret2.result.data.status==='completed')
          {
            MessageList(chatContext.value)
            .then(ret3=>{
              console.log(JSON.stringify(ret3))
              if(ret3.result.code==0)
              {
                //TODO:显示文章
                articleContent.value= ret3.result.data[0].content
                let title=articleContent.value.split('\n')[1]
                let content=articleContent.value.replace('=====','')
                emits('onComplete',{title:title,content:content})
                ret3.result.data.forEach((item,index)=>{
                    if(item.type=='follow_up')  //answer verbose
                    {
                      followUp.value.push(item.content)
                    }

                })

              }else
              {
                MessagePlugin.error(ret3.result.msg)
              }
            })
            clearInterval(timer)
            chatStatus.value=0

          }
        })
      },1000)

    })
  }

const openTokenPage=()=>{
  visibleTokenPage.value=false
  router.push('/settings/base')
}
const visibleTokenPage=ref(false)


  watch(()=>props.visible,
  ()=>{
    visibleDrawer.value=props.visible
  })
</script>

<style>
</style>
